package com.langyiquan.service.impl;

import com.langyiquan.bo.CarouselBO;
import com.langyiquan.mapper.CarouselMapper;
import com.langyiquan.pojo.Carousel;
import com.langyiquan.service.CarouselService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class CarouselServiceImpl implements CarouselService {

    @Autowired
    private CarouselMapper carouselMapper;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Carousel> queryAll(Date startTime, Date endTime) {
        Example example = new Example(Carousel.class);
        example.orderBy("sort").desc();
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("startTime",startTime);
        criteria.andGreaterThanOrEqualTo("endTime",endTime);
        List<Carousel> result = carouselMapper.selectByExample(example);
        return result;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Carousel queryCarouselInfo(Integer carouselId) {
        Carousel carousel = carouselMapper.selectByPrimaryKey(carouselId);
        return carousel;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Carousel createCarousel(CarouselBO carouselBO) {

        Carousel carousel = new Carousel();
        carousel.setImageUrl(carouselBO.getImageUrl());
        carousel.setTargetId(carouselBO.getTargetId());
        carousel.setType(carouselBO.getType());
        carousel.setStartTime(carouselBO.getStartTime());
        carousel.setEndTime(carouselBO.getEndTime());
        carousel.setCreatedTime(new Date());
        carousel.setUpdatedTime(new Date());
        carouselMapper.insert(carousel);
        return carousel;

    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Carousel updateCarousel(Integer carouselId, CarouselBO carouselBO) {
        Carousel carousel = new Carousel();
        BeanUtils.copyProperties(carouselBO,carousel);
        carousel.setId(carouselId);
        carousel.setImageUrl(carouselBO.getImageUrl());
        carousel.setTargetId(carouselBO.getTargetId());
        carousel.setType(carouselBO.getType());
        carousel.setStartTime(carouselBO.getStartTime());
        carousel.setEndTime(carouselBO.getEndTime());
        carousel.setUpdatedTime(new Date());
        carouselMapper.updateByPrimaryKeySelective(carousel);
        return queryCarouselInfo(carouselId);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer deleteCarousel(Integer carouselId) {
        return carouselMapper.deleteByPrimaryKey(carouselId);
    }


}
